
package cn.group_06.bookmanager.JFrame;
import java.util.UUID;

import redis.clients.jedis.exceptions.JedisConnectionException;


import cn.group_06.bookmanager.dao.UserDao;
import javax.swing.JPasswordField;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import redis.clients.jedis.Jedis;
import com.google.gson.Gson;
import redis.clients.jedis.Jedis;

import cn.group_06.bookmanager.model.User;
import cn.group_06.bookmanager.utils.DbUtil;
import cn.group_06.bookmanager.utils.toolUtil;
import cn.group_06.bookmanager.utils.re;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;

public class LoginFrm extends JFrame {
	public static User currentUser;
	private JFrame jf;
	private JTextField userNameText;
	private JTextField passwordText;
	private JComboBox<String> comboBox;
    re r=new re();
	UserDao userDao = new UserDao();
	DbUtil dbUtil = new DbUtil();
	public LoginFrm(){
				
		jf=new JFrame("超市进销存系统");
		jf.getContentPane().setFont(new Font("幼圆", Font.BOLD, 14));
		jf.setBounds(600, 50, 500, 467);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.getContentPane().setLayout(null);

		

		
		JLabel label = new JLabel("用户名：");
		label.setFont(new Font("幼圆", Font.BOLD, 14));
		label.setBounds(129, 50, 100, 29);
		jf.getContentPane().add(label);
		
		userNameText = new JTextField();
		userNameText.setBounds(199, 52, 167, 25);
		jf.getContentPane().add(userNameText);
		userNameText.setColumns(10);
		
		JLabel label_1 = new JLabel("密码：");
		label_1.setFont(new Font("幼圆", Font.BOLD, 14));
		label_1.setBounds(144, 89, 100, 29);
		jf.getContentPane().add(label_1);
		
		passwordText = new JPasswordField();
		//passwordText = new JTextField();
		passwordText.setColumns(10);
		passwordText.setBounds(199, 91, 167, 25);
		jf.getContentPane().add(passwordText);
		
		JButton button = new JButton("登录");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkLogin(e);
			}
		});
		button.setBounds(153, 177, 65, 29);
		jf.getContentPane().add(button);
		

		jf.setVisible(true);
		jf.setResizable(true);
		
	}

	/*protected void regUser(ActionEvent e) {
		jf.setVisible(false);
		new RegFrm();
		
	}*/
	
	
	/*
	protected void checkLogin(ActionEvent e) {
		String userName = userNameText.getText();
		String password = passwordText.getText();
		
		//
		//if (toolUtil.isEmpty(userName) || toolUtil.isEmpty(password)) {
			//JOptionPane.showMessageDialog(null, "数据不能为空");
			//return;
		//}
		
		
		Jedis jedis = re.getJedis();
		Gson gson = new Gson();
		String empJson = jedis.get("employee:" + userName);

		if (empJson != null) {
			currentUser = gson.fromJson(empJson, User.class);
			if (currentUser != null && currentUser.getPassword().equals(password)) {
				handleLoginSuccess(jedis);
				return;
			}
		}

		
		User user = new User();
		user.setUserName(userName);
		user.setPassword(password);

		Connection con = null;
		try {
			con = dbUtil.getConnection();
			User login = userDao.login(con, user);
			currentUser = login;
			if (login == null) {
				JOptionPane.showMessageDialog(null, "登录失败");
			} else {
				jf.dispose();
				new Maininfo("");
			}
		} catch (Exception e21) {

			e21.printStackTrace();
			JOptionPane.showMessageDialog(null, "login fail");
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e31) {

				e31.printStackTrace();
			}
		}
		
	}

	private void handleLoginSuccess(Jedis jedis) {
		jedis.set("current_user", new Gson().toJson(currentUser));
		this.setVisible(false);
		//if (currentUser.getElevel().equals("00")) {
			new LoginFrm();
		}
	
	public static void main(String[] args) {
		try {

		} catch (Exception e) {
			e.printStackTrace();
		}
		new LoginFrm();
	
}
}
	*/
	
	
	 /*
	protected void checkLogin(ActionEvent e) {
	    String userName = userNameText.getText();
	    // 注意这里是使用 JPasswordField 的 getPassword() 方法
	    //    char [] passwordChars = passwordText.getPassword();
	   // String password = new String(passwordChars);
	    
	    //char [] password =new String(passwordText.getPassword()) ;
	    
	 

	    char[] password = ((JPasswordField)passwordText).getPassword();
	    
	    Jedis jedis = re.getJedis();
	    if (jedis == null) {
	    
	        JOptionPane.showMessageDialog(jf, "Redis 连接失败", "错误", JOptionPane.ERROR_MESSAGE);
	        return;
	    }

	    try {
	    	
	        // 从Redis中获取存储的密码
	        String storedPassword = jedis.get("password:" + userName);
	        
	      
	        // 检查密码是否匹配
	        if (storedPassword != null && password.equals(storedPassword)) {
	            handleLoginSuccess();
	        } else {
	        	
	            JOptionPane.showMessageDialog(jf, "密码错误", "登录失败", JOptionPane.ERROR_MESSAGE);
	        }
	    } catch (Exception ex) {
	        ex.printStackTrace();
	        JOptionPane.showMessageDialog(jf, "登录时发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
	    } finally {
	        // 关闭Redis连接
	        if (jedis != null) {
	            jedis.close();
	        }
	    }
	}
	*/
	protected void checkLogin(ActionEvent e) {
	    String userName = userNameText.getText();
	    char[] passwordChars = ((JPasswordField)passwordText).getPassword();
	    String password = new String(passwordChars);

	    Jedis jedis = re.getJedis();
	    if (jedis == null) {
	        JOptionPane.showMessageDialog(jf, "Redis 连接失败，请检查服务器状态。", "错误", JOptionPane.ERROR_MESSAGE);
	        return;
	    }

	    Gson gson = new Gson(); // Google Gson 用于 JSON 序列化和反序列化
	    String key = "user:" + userName; // 构建键名，您可能需要根据实际情况调整前缀

	    try {
	        // 检查用户键是否存在
	        if (jedis.exists(key)) {
            // 键存在，获取JSON格式的用户信息
	            String userJson = jedis.get(key);
	            // 反序列化JSON字符串到User对象
	            User user = gson.fromJson(userJson, User.class);
	            // 检查密码是否匹配
	            if (user != null && user.getPassword().equals(password)) {
	                handleLoginSuccess(); // 密码匹配，处理登录成功逻辑
	            } else {
	                JOptionPane.showMessageDialog(jf, "密码错误或用户不存在。", "登录失败", JOptionPane.ERROR_MESSAGE);
	            }
	        } else {
	            // 键不存在，可能需要查询数据库以验证用户
	            // 这里假设您有一个方法来查询数据库并返回User对象
	            User user = userDao.findByUsername(userName);
	            if (user != null && user.getPassword().equals(password)) {
	                // 如果数据库验证成功，序列化用户信息并存储到Redis
	                jedis.set(key, gson.toJson(user));
	                handleLoginSuccess(); // 处理登录成功逻辑
	            } else {
	                JOptionPane.showMessageDialog(jf, "用户不存在或密码错误。", "登录失败", JOptionPane.ERROR_MESSAGE);
	            }
	        }
	    } catch (JedisConnectionException jce) {
	        JOptionPane.showMessageDialog(jf, "连接到 Redis 时发生错误，请检查连接设置。", "错误", JOptionPane.ERROR_MESSAGE);
	    } catch (Exception ex) {
	        ex.printStackTrace();
	        JOptionPane.showMessageDialog(jf, "登录时发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
	    } finally {
	        if (jedis != null) {
	            jedis.close(); // 关闭 Jedis 连接
	        }
	    }
	}

	private void handleLoginSuccess() {
	    // 登录成功后的操作，例如：
	    jf.setVisible(false);
	    // 打开主界面或其他操作
	     new Maininfo(""); // 假设这是您的主界面类
	}
	// 您需要实现这个数据库查询方法
		public static void main(String[] args) {
		/*
		try {

		} catch (Exception e) {
			e.printStackTrace();
		}
		new LoginFrm();
		*/
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            re.closeJedis();
        }));
		int newEmpId=30;
        new LoginFrm();
	}
}
